﻿using System;
using System.Collections.Generic;
using System.Web;


namespace CCPSIP.vCardGE
{
    /// <summary>CCPSIP_055：群組名片交換 - 環境偵測 API</summary>

    public class detect : IHttpHandler
  {
    private const int kHAccuracyLimit = 100 * 1000; //in meters


    public void ProcessRequest(HttpContext context) {
      HttpRequest req = context.Request;
      HttpResponse resp = context.Response;
      resp.ContentType = "text/plain";
      resp.ContentEncoding = System.Text.Encoding.UTF8;
      DateTime reqTime = DateTime.Now;
      string resultStr = "";


      try {
        //【01】取得POST參數，驗證身分
        //
        string idHeader = req.Form["idHeader"];
        string checkcode = req.Form["checkcode"];
        decimal latitude = -1; //緯度
        decimal longitude = -1;//經度
        int hAccuracy = -1;//誤差半徑(meter)
        LocationInfo location = null;

        try {
          latitude = Math.Round(Convert.ToDecimal(req.Form["latitude"]), 6);
          longitude = Math.Round(Convert.ToDecimal(req.Form["longitude"]), 6);
          hAccuracy = Convert.ToInt32(Convert.ToDecimal(req.Form["hAccuracy"]));
          if (hAccuracy > kHAccuracyLimit)
            throw new Exception();
          location = new LocationInfo(reqTime, latitude, longitude, hAccuracy);
        }
        catch {
          throw new Exception("Error_01: Parameter Error");//參數錯誤
        }

        SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
        if (userInfo == null) {
          throw new Exception("Error_02: Cannot identify this device");//無法識別此裝置
        }


        //【02】取得附近的群組名片交換資訊
        //
        Dictionary<string, string>[] dictArray = OracleKitVCardGE.getNearbyVCardGE(location);


        //【99】以JSON格式回傳
        //
        resp.ContentType = "application/json";
        resp.Charset = null;
        fastJSON.JSON.Instance.Parameters.EnableAnonymousTypes = true;
        resultStr = fastJSON.JSON.Instance.ToJSON(dictArray);
      }
      catch (Exception ex) {
        resp.ContentType = "application/xml";
        resultStr = ChrisKit.Ex2Xml(ex, false);
      }
      finally {
        int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
        resp.AppendHeader("Content-Length", contentLength.ToString());
        resp.Write(resultStr);
        resp.Flush();
        resp.Close();
      }
    }


    public bool IsReusable {
      get {
        return false;
      }
    }

  }
}
